<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AlterTableDormMeterRecords extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('dorm_meter_records', function (Blueprint $table) {
            if (!Schema::hasColumn('dorm_meter_records', 'prev_reading_date')) {
                $table->date('prev_reading_date')->nullable()->after('prev_meter_reading');
            }
        });
        $sql = <<<SQL
UPDATE dorm_meter_records
SET prev_reading_date = DATE_SUB(meter_reading_date, INTERVAL day_span DAY);
SQL;
        DB::unprepared($sql);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('dorm_meter_records', function (Blueprint $table) {
            $table->dropColumn('prev_reading_date');
        });
    }
}
